var records = require("./data/user.json");
var fs = require('fs');

var _filename = __dirname + "/data/" + "user.json";

var queryById = function(id) {
	for(var i = 0, len = records.length; i < len; i++) {
		var record = records[i];
		if(record.id == id) {
			return record;
		}
	}
}
exports.findAll = function(id, cb) {
	return records;
}

exports.findByIdNoCb = function(id) {
	return queryById(id);
}

exports.findById = function(id, cb) {
	process.nextTick(function() {
		return cb(null, queryById(id));
	});
}

exports.findByUsername = function(username, cb) {
	process.nextTick(function() {
		for(var i = 0, len = records.length; i < len; i++) {
			var record = records[i];
			if(record.username === username) {
				return cb(null, record);
			}
		}
		return cb(null, null);
	});
}

exports.deleteById = function(id) {
	process.nextTick(function() {
		records.forEach(function(e, i) {
			if(e.id == id) {
				records.splice(i, 1);
				return;
			}
		});
		fs.writeFileSync(_filename, JSON.stringify(records));
	});
}

exports.update = function(user) {
	process.nextTick(function() {
		for(var i = 0, len = records.length; i < len; i++) {
			if(records[i].id == user.id) {
				records[i] = {
					id: user.id,
					username: user.username,
					password: records[i].password,
					email: user.email,
					nickname: user.nickname,
					icon: records[i].icon
				}
				break;
			}
		}
		fs.writeFileSync(_filename, JSON.stringify(records));
	});
}

exports.add = function(nickname, username, password, email, filename) {
	process.nextTick(function() {
		var id = 1;
		if(records.length > 0) {
			id = parseInt(records[records.length - 1].id) + 1;
		}
		records.push({
			"id": id,
			"username": username,
			"password": password,
			"email": email,
			"nickname": nickname,
			"icon": filename
		});
		fs.writeFileSync(_filename, JSON.stringify(records));
	});
}